package com.redwinter.logkit.support.service;

import ch.qos.logback.classic.AsyncAppender;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import com.redwinter.logkit.support.api.LogCollectService;
import com.redwinter.logkit.support.appender.LogAppender;
import com.redwinter.logkit.support.config.LogProperties;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author goudadong
 * @description 日志收集抽象基类
 * @datetime 2021-12-16 17:35
 * @email 2360564660@qq.com
 **/
public abstract class AbstractLogCollect implements LogCollectService {

    private static final Map<String, Logger> LOGGER_MAP = new HashMap<>();
    private static final String BIZ_FILE = "BIZ-LOGGER-";
    private final LogProperties logProperties;

    public AbstractLogCollect(LogProperties logProperties) {
        this.logProperties = logProperties;
    }

    protected Logger getLogger(String fileName) {
        String key = BIZ_FILE + fileName;
        Logger logger = LOGGER_MAP.get(key);
        if (Objects.isNull(logger)) {
            synchronized (this) {
                logger = LOGGER_MAP.get(key);
                if (Objects.isNull(logger)) {
                    logger = buildLogger(key, fileName);
                    LOGGER_MAP.put(key, logger);
                }
            }
        }
        return logger;
    }

    private Logger buildLogger(String name, String fileName) {
        AsyncAppender infoAppender = new LogAppender(logProperties).asyncAppender(name, fileName, Level.INFO);
        LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
        Logger logger = context.getLogger(LogAppender.ASYNC_FILE + name);
        logger.setAdditive(true);
        logger.addAppender(infoAppender);
        return logger;
    }
}
